package com.guang.springbootmybatisbatchoperate.batch;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * @author liguang
 * @date 2022/6/13 17:22
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(value = {SqlSessionFactoryBean.class,SqlSessionTemplate.class})
public class BatchConfig {


    @Primary
    @Bean(name = {"simpleSqlSessionTemplate","sqlSessionTemplate"})
    public SqlSessionTemplate simpleSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory, ExecutorType.SIMPLE);
    }

    @Bean(name = {"batchSqlSessionTemplate"})
    public SqlSessionTemplate batchSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory, ExecutorType.BATCH);
    }

    @Bean(name = {"mapperBatchExecutor"})
    @ConditionalOnClass({SqlSessionTemplate.class})
    @ConditionalOnBean(value = {SqlSessionTemplate.class}, name = {"batchSqlSessionTemplate"})
    public MapperBatchExecutor mapperBatchExecutor(@Qualifier("batchSqlSessionTemplate") SqlSessionTemplate batchSqlSessionTemplate) {
        return new MapperBatchExecutor(batchSqlSessionTemplate);
    }
}
